package com.iflytek.jzcpx.procuracy.tools.roma;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;

/**
 * hw roma request util
 * 
 * @author dgyu
 *
 */
@Component
public class RomaUtil {

	private static final Logger logger = LoggerFactory.getLogger(RomaUtil.class);

	@Value("${roma.url}")
	private String requestURL;

	@Value("${roma.key}")
	private String key;

	@Value("${roma.secret}")
	private String secret;

	@Value("${roma.version}")
	private String csbVersion;

	@Value("${roma.apiName.file2DoublePdf}")
	private String apiNameFile2DoublePdf;

	@Value("${roma.version}")
	private String versionFile2DoublePdf;

	@Value("${roma.apiName.saveDZJZSBZT}")
	private String apiNameSaveDZJZSBZT;

	@Value("${roma.version}")
	private String versionSaveDZJZSBZT;

	@Value("${roma.apiName.cont.jzmlwj}")
	private String roma_apiName_cont_jzmlwj;// roma.apiName.cont.jzmlwj=dzjz-api-2003

	@Value("${roma.version}")
	private String roma_version_cont_jzmlwj; // roma.version.cont.jzmlwj=1.0.0

	@Value("${roma.apiName.cont.jzmlwj.jpg}")
	private String roma_apiName_cont_jzmlwj_jpg;//// roma.apiName.cont.jzmlwj.jpg=dzjz-api-2004

	@Value("${roma.version}")
	private String roma_version_cont_jzmlwj_jpg; // roma.version.cont.jzmlwj.jpg=1.0.0

	@Value("${roma.apiName.cont.jzmlwj.save}")
	private String roma_apiName_cont_jzmlwj_save; // roma.apiName.cont.jzmlwj.save=dzjz-api-2005

	@Value("${roma.version}")
	private String roma_version_cont_jzmlwj_save; // roma.version.cont.jzmlwj.save=1.0.0

	@Value("${roma.apiName.ocr.dzjz.un_ocr}")
	private String roma_apiName_ocr_dzjz_un_ocr; // roma.apiName.ocr.dzjz.un_ocr=dzjz-api-2006

	@Value("${roma.version}")
	private String roma_version_ocr_dzjz_un_ocr; // roma.version.ocr.dzjz.un_ocr=1.0.0

	@Value("${roma.apiName.ocr.dzjz.jpg}")
	private String roma_apiName_ocr_dzjz_jpg; // roma.apiName.ocr.dzjz.jpg=dzjz-api-2007

	@Value("${roma.version}")
	private String roma_version_ocr_dzjz_jpg; // roma.version.ocr.dzjz.jpg=1.0.0

	@Value("${roma.apiName.ocr.dzjz.savepdf}")
	private String roma_apiName_ocr_dzjz_savepdf; // roma.apiName.ocr.dzjz.savepdf=dzjz-api-2008

	@Value("${roma.version}")
	private String roma_version_ocr_dzjz_savepdf; // roma.version.ocr.dzjz.savepdf=1.0.0

	@Value("${roma.apiName.ocr.dzjz.saveOcrStatus}")
	private String roma_apiName_ocr_dzjz_saveOcrStatus; // roma.apiName.ocr.dzjz.saveOcrStatus=dzjz-api-2009

	@Value("${roma.version}")
	private String roma_version_ocr_dzjz_saveOcrStatus; // roma.version.ocr.dzjz.saveOcrStatus=1.0.0

	@Value("${roma.apiName.card.ajxx}")
	private String apiName_GetAJXX;

	@Value("${roma.apiName.card.ajwswj}")
	private String apiName_GetAJWSWJ;

	@Value("${roma.apiName.card.ajwsjzwj}")
	private String apiName_GetAJWSJZWJ;

	/**
	 * @param jsonString
	 * @return
	 */
	public String doPostRomaApiNameContJzmlwj(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	/**
	 * @param jsonString
	 * @return
	 */
	public String doPostRomaApiNameContJzmlwjJpg(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	public String doPostRomaApiNameContJzmlwjSave(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	public String doPostRomaApiNameOcrDzjzUn_ocr(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	public String doPostRomaApiNameOcrDzjzJpg(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	public String doPostRomaApiNameOcrDzjzSavepdf(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	public String doPostRomaApiNameOcrDzjzSaveOcrStatus(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	/**
	 * OCR mq接口中，获取批量ocr原始图片的接口
	 *
	 * @param jsonString 入参
	 * @return
	 */
	public String getOCRFileInfo(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	/**
	 * OCR mq接口中，保存OCR识别结果
	 *
	 * @param jsonString 入参
	 * @return
	 */
	public String saveDZJZSBZT(String jsonString) {
		String result = null;
		result = buildRomaRequest(jsonString, null);
		return result;
	}

	/**
	 * 获取案件文书文件
	 * 
	 * @param body 请求体
	 * @return 文件流
	 */
	public byte[] getAJWSWJ(String body) {
		String resp = null;
		try {
			resp = buildRomaRequest(body, null);
			if (StringUtils.isBlank(resp)) {
				logger.info("获取案件文书文件响应结果为空, body: {}", body);
				return null;
			}
		} catch (Exception e) {
			logger.error("调用华为APIGETWAY, 获取案件文书卷宗文件错误, body: {}", body, e);
			return null;
		}
		try {
			JSONObject respJson = JSONObject.parseObject(resp);
			if (respJson.getBooleanValue("success")) {
				return respJson.getBytes("data");
			} else {
				logger.info("获取案件文书文件响应结果为失败. body: {}, resp: {}", body, resp);
			}
		} catch (Exception e) {
			logger.warn("获取案件文书文件响应内容解析错误, body: {}, resp: {}", body, resp, e);
		}
		return null;
	}

	/**
	 * 获取案件文书卷宗文件
	 *
	 * @param body 请求体
	 * @return wjmc: 文件名称; wjkzm: 文件扩展名; wjl: 文件流(byte[])
	 */
	public JSONObject getAJWSJZWJ(String body) {
		String resp = null;
		try {
			resp = buildRomaRequest(body, null);
			if (StringUtils.isBlank(resp)) {
				logger.info("获取案件文书卷宗文件响应结果为空, body: {}", body);
				return null;
			}
		} catch (Exception e) {
			logger.error("调用华为APIGETWAY, 获取案件文书卷宗文件错误, body: {}", body, e);
			return null;
		}
		try {
			JSONObject respJson = JSONObject.parseObject(resp);
			if (respJson.getBooleanValue("success")) {
				return respJson.getJSONObject("data");
			} else {
				logger.info("获取案件文书卷宗文件响应结果为失败. body: {}, resp: {}", body, resp);
			}
		} catch (Exception e) {
			logger.warn("获取案件文书卷宗文件响应内容解析错误, body: {}, resp: {}", body, resp, e);
		}
		return null;
	}

	/**
	 * 获取案件信息
	 *
	 * @param body 请求体
	 *
	 */
	public JSONObject getAJXX(String body) {
		String resp = null;
		try {
			resp = buildRomaRequest(body, null);
			if (StringUtils.isBlank(resp)) {
				logger.info("获取案件信息响应结果为空, body: {}", body);
				return null;
			}
		} catch (Exception e) {
			logger.error("调用阿里云CSB, 获取案件信息错误, body: {}", body, e);
			return null;
		}
		try {
			JSONObject respJson = JSONObject.parseObject(resp);
			if (respJson.getBooleanValue("success")) {
				return (JSONObject) respJson.getJSONArray("data").get(0);
			} else {
				logger.info("获取案件信息响应结果为失败. body: {}, resp: {}", body, resp);
			}
		} catch (Exception e) {
			logger.warn("获取案件信息内容解析错误, body: {}, resp: {}", body, resp, e);
		}
		return null;
	}

	private String buildRomaRequest(String body, String method) {
		// Create a new request.
		CloseableHttpClient client = null;
		try {
			Request request = new Request();
			// Set the request parameters.
			// AppKey, AppSecrect, Method and Url are required parameters.
			request.setKey(key);
			request.setSecret(secret);
			request.setMethod(StringUtils.isEmpty(method) ? "POST" : method);////////
			request.setUrl(requestURL);
			request.addHeader("Content-Type", "application/json; charset=UTF-8");//////////////
			// if it was published in other envs(except for Release),you need to add the
			// information x-stage and the value is env's name
			// request.addHeader("x-stage", "publish_env_name");
			request.setBody(body);////////////
			// Sign the request.
			HttpRequestBase signedRequest = Client.sign(request);
			// Send the request.
			client = HttpClients.custom().build();
			HttpResponse response = client.execute(signedRequest);
			// Print the status line of the response.
			logger.debug("roma respomse status:{}", response.getStatusLine().toString());
			// Print the header fields of the response.
			Header[] resHeaders = response.getAllHeaders();
			for (Header h : resHeaders) {
				logger.debug("roma respomse header:{} ", h.getName() + ":" + h.getValue());
			}
			// Print the body of the response.
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				// logger.debug(System.getProperty("line.separator") +
				// EntityUtils.toString(resEntity, "UTF-8"));
				return EntityUtils.toString(resEntity, "UTF-8");
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("request");
			return null;
		} finally {
			try {
				if (client != null) {
					client.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
